package com.qilu.pe.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.StringUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.ExReportDetailsResult;
import com.qilu.pe.dao.bean.IndicatorStandard;
import com.qilu.pe.dao.bean.ReportDetail;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.ActiviceCollector;
import com.qilu.pe.support.util.GlideUtil;
import com.qilu.pe.support.util.PeUtil;
import com.qilu.pe.ui.adapter.IndicatorStandardAdapter;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseActivity;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.ToastUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import io.reactivex.functions.Consumer;

// 解读详情
public class ExplainDetailActivity extends Base2Activity {

    private IndicatorStandardAdapter adapter;// 检测以及指标列表adapter
    private String id;
    private String mExplainTime;
    private ExReportDetailsResult details;
    private TextView tv_name, tv_out_order_name, tv_sex_age, vExpertName, vExplainTime, vExplainContent;
    private RoundedImageView vExpertAvatar;
    private RecyclerView rcv_indicator_standard, vImagesGrid;
    private TextView vHeight, vHeart, vBlood, vBlood2, vWeight, vTemperature, vFamily, vDrug, vTreatment, vAllergy, vText;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_explain_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActiviceCollector.addActivity(this);
        rcv_indicator_standard = findViewById(R.id.rcv_indicator_standard);
        id = getIntent().getStringExtra("id");
        mExplainTime = getIntent().getStringExtra("explainTime");

        setNavigationIcon(R.mipmap.ic_left_arrow);
        setHeadTitle("解读详情");

        initView();
        initData();
    }

    public void initView() {
        tv_name = findViewById(R.id.tv_name);
        tv_out_order_name = findViewById(R.id.tv_out_order_name);
        tv_sex_age = findViewById(R.id.tv_sex_age);
        vExpertAvatar = findViewById(R.id.vExpertAvatar);
        vExpertName = findViewById(R.id.vExpertName);
        vExplainTime = findViewById(R.id.vExplainTime);
        vExplainContent = findViewById(R.id.vExplainContent);
        rcv_indicator_standard = findViewById(R.id.rcv_indicator_standard);
        vHeight = findViewById(R.id.vHeight);
        vHeart = findViewById(R.id.vHeart);
        vBlood = findViewById(R.id.vBlood);
        vBlood2 = findViewById(R.id.vBlood2);
        vWeight = findViewById(R.id.vWeight);
        vTemperature = findViewById(R.id.vTemperature);
        vFamily = findViewById(R.id.vFamily);
        vDrug = findViewById(R.id.vDrug);
        vTreatment = findViewById(R.id.vTreatment);
        vAllergy = findViewById(R.id.vAllergy);
        vText = findViewById(R.id.vText);
        vImagesGrid = findViewById(R.id.vImagesGrid);

        findViewById(R.id.tv_detail).setOnClickListener(this);
    }

    public void initData() {
        showProgress();
        APIRetrofit.getDefault().getReportDetail(Global.HEADER, id)
                .compose(RxUtil.<BaseResult2<ExReportDetailsResult>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<ExReportDetailsResult>>() {
                    @Override
                    public void accept(BaseResult2<ExReportDetailsResult> res) throws Exception {
                        hideProgress();
                        if (res.isSuccess()) {
                            details = res.getData();
                            loadView();
                        } else {
                            ToastUtils.showShort(res.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    public void loadView() {
        ExReportDetailsResult.UserInfo user = details.getUser_info();
        tv_name.setText(user.getName());
        Date birthDate = new Date();
        try {
            birthDate = new SimpleDateFormat("yyyy-MM").parse(user.getBirth());
        } catch (Exception e) {
            e.printStackTrace();
        }
        Calendar birth = Calendar.getInstance();
        birth.setTime(birthDate);
        Calendar now = Calendar.getInstance();
        tv_sex_age.setText(String.format("性别：%1$s    年龄：%2$s", "0".equals(user.getSex()) ? "男" : "女", now.get(Calendar.YEAR) - birth.get(Calendar.YEAR)));
        tv_out_order_name.setText(String.format("出单人：%1$s", details.getUsername()));

        ExReportDetailsResult.ReportInfo report = details.getReport_info();
        GlideUtil.loadImg(PeUtil.getImageUrl(user.getPicture()), vExpertAvatar);
        vExpertName.setText(String.format("专家：%1$s", report.getName()));
        vExplainTime.setText(String.format("解读时间：%1$s", mExplainTime));
        vExplainContent.setText(report.getContent());

        vHeight.setText(String.format("身高：%1$s", user.getHeight()));
        vHeart.setText(String.format("心率：%1$s", user.getHeart()));
        String[] bloodArray = new String[2];
        if (user.getBlood().contains("-")) {
            bloodArray = user.getBlood().split("-");
        } else if (user.getBlood().contains(",")) {
            bloodArray = user.getBlood().split(",");
        }
        vBlood.setText(String.format("收缩压：%1$s", bloodArray[0]));
        vBlood2.setText(String.format("舒张压：%1$s", bloodArray[1]));
        vWeight.setText(String.format("体重：%1$s", user.getWeight()));
        vTemperature.setText(String.format("体温：%1$s", user.getTemperature()));
        vFamily.setText(String.format("家族史：%1$s", user.getFamily()));
        vDrug.setText(String.format("用药史：%1$s", user.getDrug()));
        vTreatment.setText(String.format("治疗史：%1$s", user.getTreatment()));
        vAllergy.setText(String.format("过敏史：%1$s", user.getAllergy()));
        vText.setText(String.format("主要不适及临床表现：%1$s", StringUtils.isEmpty(report.getText()) ? "" : report.getText()));

        vImagesGrid.setLayoutManager(new GridLayoutManager(this, 3));
        ImageGridAdapter imgAdapter = new ImageGridAdapter(this);
        vImagesGrid.setAdapter(imgAdapter);
        imgAdapter.setDataList(report.getImage());

        LinearLayoutManager manager = new LinearLayoutManager(this);
        adapter = new IndicatorStandardAdapter(this);
        rcv_indicator_standard.setLayoutManager(manager);
        rcv_indicator_standard.setAdapter(adapter);
        adapter.setDataList(details.getTarget_list());
    }

    public class IndicatorStandardAdapter extends ListBaseAdapter<ExReportDetailsResult.TargetItem> {
        public IndicatorStandardAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_indicator_standard_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            TextView tv_item_val = holder.getView(R.id.tv_item_val);// 指标项
            TextView tv_code_val = holder.getView(R.id.tv_code_val);// 代码
            TextView tv_test_val = holder.getView(R.id.tv_test_val);// 检测值
            TextView tv_reference_val = holder.getView(R.id.tv_reference_val);// 参考值

            ExReportDetailsResult.TargetItem info = mDataList.get(position);
            tv_item_val.setText(info.getHosprptitemname());
            tv_code_val.setText(info.getHosprptitemcode());
            tv_test_val.setText(info.getResult_str());
            tv_reference_val.setText(info.getResult_ref());
        }
    }

    public class ImageGridAdapter extends ListBaseAdapter<String> {
        public ImageGridAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_image_grid;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            RoundedImageView img = holder.itemView.findViewById(R.id.vImage);
            GlideUtil.loadImg(PeUtil.getImageUrl(mDataList.get(position)), img);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_detail:
                Bundle bundle = new Bundle();
                bundle.putString("order_id", id);
                startActivity(ReportDetailActivity.class, bundle);
                break;
        }
    }
}